package com.edyd.customer.api.interceptor;

import com.edyd.customer.api.context.ActionContext;
import com.edyd.customer.api.domain.Customer;
import com.edyd.customer.api.service.CustomerService;
import com.fow.core.platform.exception.UserAuthorizationException;
import com.fow.core.platform.http.HTTPHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by greg.chen on 14-10-21.
 */
@Order(2)
public class SessionInterceptor extends HandlerInterceptorAdapter {

    private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SessionInterceptor.class);


    @Autowired
    private CustomerService customerService;

    @Autowired
    private ActionContext actionContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("SessionInterceptor ----------preHandle------------, URI=" +request.getRequestURI());


        //如果Annotation标识有LoginRequired, 判断method是否含有customer session
        checkLoginRequired(handler, request);

        return true;
    }

    private void checkLoginRequired(Object handler, HttpServletRequest request) {


        if(((HandlerMethod) handler).getMethod().isAnnotationPresent(LoginRequired.class)){

            int customerId = 0;

            try {
                customerId = Integer.parseInt(request.getHeader(HTTPHeaders.HEADER_CUSTOMER_ID));
            }
            catch (NumberFormatException e){
                throw new UserAuthorizationException("login required");
            }

            if(customerId <= 0)
                throw new UserAuthorizationException("login required");

            request.setAttribute(HTTPHeaders.HEADER_CUSTOMER_ID,customerId);

            Customer customer = actionContext.getCustomer();
            if(customer == null)
                throw new UserAuthorizationException("login required");

            request.setAttribute(ActionContext.CURRENT_CUSTOMER, customer);

            customerService.updateCache(customer, customer.getId());
        }
    }

}

